package cn.xiaolang.function.sharding;

import cn.xiaolang.common.utils.CRC16Util;
import org.springframework.util.StopWatch;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * crc16跟hashcode比对
 *
 * @author fuhw/DeanKano
 * @date 2019-04-17 16:40
 */
public class ShardingSample {
    private static int threshold = 4;

    public static void main(String[] args) {

        List[] hashList = {new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList()};
        List[] crcList = {new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList()};
        List[] bitList = {new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList()};

        int batchSize = 10000000;
//        crcShardingByDelivery(batchSize, crcList);
        hashShardingByDelivery(batchSize, hashList);
        bitShardingByDelivery(batchSize, bitList);
    }

    private static void crcShardingByDelivery(int size, List[] crcList) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        for (int i = 0; i < size; i++) {
            String temp = UUID.randomUUID().toString();
            int crcIndex = CRC16Util.calculateCRC16(temp.getBytes()) % threshold;
            crcList[crcIndex].add(i);
        }
        stopWatch.stop();
        System.out.println("crc handler：" + size + ">耗时(ms)：" + stopWatch.getTotalTimeMillis());
        for (int i = 0; i < threshold; i++) {
            System.out.println("crc-" + i + " : " + crcList[i].size());
        }
    }

    private static void hashShardingByDelivery(int size, List[] hashList) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        for (int i = 0; i < size; i++) {
            String temp = UUID.randomUUID().toString();
            int hashIndex = Math.abs(temp.hashCode()) % threshold;
            hashList[hashIndex].add(i);
        }
        stopWatch.stop();
        System.out.println("hash handler：" + size + ">耗时(ms)：" + stopWatch.getTotalTimeMillis());
        for (int i = 0; i < threshold; i++) {
            System.out.println("hash-" + i + " : " + hashList[i].size());
        }
    }

    private static void bitShardingByDelivery(int size, List[] bitList) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        for (int i = 0; i < size; i++) {
            String temp = UUID.randomUUID().toString();
            int hashIndex = Math.abs(temp.hashCode()) & (threshold - 1);
            bitList[hashIndex].add(i);
        }
        stopWatch.stop();
        System.out.println("bit handler：" + size + ">耗时(ms)：" + stopWatch.getTotalTimeMillis());
        for (int i = 0; i < threshold; i++) {
            System.out.println("bit-" + i + " : " + bitList[i].size());
        }
    }
}
